package cn.xsw.qrcode_login.mapper;

import cn.xsw.qrcode_login.entity.UserToken;
import org.apache.ibatis.annotations.*;

@Mapper
public interface QrTokenMapper {

    @Insert("<script>" +
            "insert into user_token (device_inf, device_type, expire_time, qc_status) values(#{deviceInf}, #{deviceType}, date_add(now(), INTERVAL 60 SECOND), 0)" +
            "</script>")
    @Options(useGeneratedKeys=true, keyProperty = "id", keyColumn = "id")
    Integer createQrToken(UserToken userToken);

    @Select("select id, user_id userId, device_inf deviceInf, device_type deviceType, token, temp_token tempToken, expire_time expireTime, qc_status qcStatus " +
            " from user_token where id = #{id} and expire_time > now() ")
    UserToken queryQrTokenById(int id);

    @Select("select id, user_id userId, device_inf deviceInf, device_type deviceType, token, temp_token tempToken, expire_time expireTime, qc_status qcStatus " +
            " from user_token where device_inf = #{deviceInf} and device_type = #{deviceType} and expire_time > now() ")
    UserToken queryQrToken(String deviceInf, String deviceType);

    @Update("<script>" +
            "update user_token set user_id = #{userId}, temp_token = #{tempToken}, expire_time = date_add(now(), INTERVAL 120 SECOND), qc_status = 1 where id = #{qrId} " +
            "</script>")
    int updateTempTokenQrTokenById(Integer qrId, Integer userId, String tempToken);

    @Select("select id, user_id userId, device_inf deviceInf, device_type deviceType, token, temp_token tempToken, expire_time expireTime, qc_status qcStatus " +
            " from user_token where id = #{qrId} and temp_token = #{tempToken} and expire_time > now() ")
    UserToken queryQrTokenByTempToken(Integer qrId, String tempToken);

    @Update("<script>" +
            "update user_token set token = #{newToken}, expire_time = date_add(now(), INTERVAL 7 DAY), qc_status = 2 where id = #{qrId} " +
            "</script>")
    int updateTokenQrTokenById(Integer qrId, String newToken);

    @Delete("delete from user_token where user_id = #{userId} or expire_time < now();")
    void removeUserTokenByUserId(Integer userId);
}
